/**
 * MGTV all right reserver
 */
package com.imgo.max.experience.service;

import com.imgo.max.artist.dto.DevoteInfo;
import com.imgo.max.common.log.CustomLogger;
import com.imgo.max.common.log.CustomLoggerFactory;
import com.imgo.max.core.utils.JsonUntils;
import com.imgo.max.experience.dao.PracticerExperienceMapper;
import com.imgo.max.experience.mapping.PracticerExperienceLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author peter.Y
 * @since 2016年4月22日
 */
@Component
public class PracticerSelfHandler {

    private static final CustomLogger logger = CustomLoggerFactory.getLogger(PracticerSelfHandler.class);

    @Resource
    PracticerExperienceMapper experienceMapper;

    @Resource
    PracticerExperienceHandler practicerExperienceHandler;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private HashOperations<String, String, String> hashRedis;

    @PostConstruct
    public void init() {
        hashRedis = stringRedisTemplate.opsForHash();
    }

    //	@Transactional
    public void record(DevoteInfo devoteInfo) {
        String uid = devoteInfo.getArtistUid(); //给艺人增加经验
        if (StringUtils.isBlank(uid)) {
            logger.warn("累加经验的练习生ID为空,忽略累加");
            return;
        }
        boolean addSuccess = false;
        try {
            int result = practicerExperienceHandler.addDbExperience(uid, devoteInfo.getDevoteValue());
            if (result > 0) {
                addSuccess = true;
                practicerExperienceHandler.freshExperience(uid);
            }
        } catch (Exception e) {
            logger.error("add practicer self experience failed, messageId: {}", devoteInfo.getMessageId(), e);
        } finally {
            try {
                PracticerExperienceLog log = new PracticerExperienceLog();
                log.setUid(devoteInfo.getArtistUid());
                log.setGiftId(devoteInfo.getGid());
                log.setMessageId(devoteInfo.getMessageId());
                log.setSource(String.valueOf(devoteInfo.getType()));//贡献来源
                log.setValue(devoteInfo.getDevoteValue());
                log.setTime(devoteInfo.getTime());
                log.setFromUid(devoteInfo.getUid());
                log.setResult(addSuccess + "");
                experienceMapper.addExperienceLog(log);
            } catch (Exception e) {
                //如果消息中包含“MQ:”,则该日志会打印到failed_message.log日志中去
                logger.error("Practicer self experience MQ:{}, add result:{}, content:{}", devoteInfo.getMessageId(), addSuccess, JsonUntils.toJson(devoteInfo), e);
            }
        }
    }


}
